package com.loveyukari.controller;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.loveyukari.model.ManageAuth;
import com.loveyukari.service.ManagerService;
import com.loveyukari.service.PhoneCodeService;
import com.loveyukari.utils.AliYunUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.loveyukari.model.PhoneCode;
import com.loveyukari.support.JsonResult;
import com.loveyukari.utils.RandomCodeUtil;

/**
*
*yangshaohua
*2017年6月12日上午11:18:29
**/
@RequestMapping(value="/login")
@Controller
public class LoginController {
	
	private Logger log = LoggerFactory.getLogger(LoginController.class);
	
	@Autowired
	private PhoneCodeService phoneCodeService;
	
	@Autowired
	private ManagerService managerService;
	
	
	@RequestMapping(value="/index")
	public String index(Model model, String message, HttpServletRequest request){
		Cookie[] cookies = request.getCookies();
		if (cookies != null){
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if (cookie.getName().equals("MANAGE_SIGN")){
					String sign = cookie.getValue();
					if (StringUtils.isNotBlank(sign)){
						ManageAuth manageAuth = managerService.getManageAuthBySign(sign);
						if (manageAuth != null){
							return "redirect:/admin/index";
						}
					}
				}
			}
		}
		if (StringUtils.isNotBlank(message)){
			model.addAttribute("message", message);
		}
		return "login";
	}

	@RequestMapping("/out")
	public String logout(HttpServletRequest request, HttpServletResponse response){
		Cookie[] cookies = request.getCookies();
		if (cookies != null){
			for (int i = 0; i < cookies.length; i++) {
				Cookie cookie = cookies[i];
				if (cookie.getName().equals("MANAGE_SIGN")){
					cookie.setMaxAge(0);
					cookie.setPath("/");
					response.addCookie(cookie);
					break;
				}
			}
		}
		return "redirect:/login/index";

	}


	@RequestMapping(value="/sign")
	@ResponseBody
	public JsonResult<String> login(HttpServletRequest request,HttpServletResponse response,String phone, String code, RedirectAttributes redirectAttributes, String uri){
		PhoneCode phoneCode = phoneCodeService.getPhoneCode(phone, code, PHONE_CODE_TYPE);
		if (phoneCode != null){
			if (System.currentTimeMillis() - phoneCode.getTime().getTime() > 15*3600*1000){
				phoneCodeService.editPhoneCodeStatus(phoneCode.getId(), 2);
				return new JsonResult<String>(-1,"登录失败","验证码超时");
			} else {
				//登录成功
				try {
					phoneCodeService.editPhoneCodeStatus(phoneCode.getId(), 1);
					String sign = managerService.getSign(phone);
					Cookie cookie = new Cookie("MANAGE_SIGN",sign);
					cookie.setMaxAge(196000000);
					cookie.setPath("/");
					response.addCookie(cookie);
					if (StringUtils.isBlank(uri)){
						uri = "/yukari/admin/index";
                    }
					return new JsonResult<String>(0,"",uri);
				} catch (Exception e) {
					return new JsonResult<String>(-1,"登录失败","手机不存在");
				}
			}
		} else {
			return new JsonResult<String>(-1,"登录失败","验证码错误");
		}
	}
	
	@RequestMapping(value="/getCode")
	@ResponseBody
	public JsonResult<String> getCode(String phone){
		if (!managerService.isLogin(phone)){
			return new JsonResult<String>(-1,"获取失败","该号码没有登陆权限");
		}
		try {
			String code = RandomCodeUtil.randomNumberCode(6);
			JsonResult<String> sendCode = AliYunUtils.sendCode(phone, code);
			if (sendCode.getCode() == 0){
				phoneCodeService.addPhoneCode(phone, code, PHONE_CODE_TYPE);
			}
			return sendCode;
		} catch (Exception e) {
			log.error(e.getMessage(),e);
			return new JsonResult<String>(-1,"服务器错误");
		}
	}
	

	
	private static final String PHONE_CODE_TYPE = "MANAGE_LOGIN";

}
